package com.situ.mvc.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.situ.mvc.common.ServerResponse;
import com.situ.mvc.dao.IRoleDao;
import com.situ.mvc.dao.impl.RoleDaoImpl;
import com.situ.mvc.entity.Role;
import com.situ.mvc.service.IRoleService;
import com.situ.mvc.util.MyBatisUtil;

public class RoleServiceImpl implements IRoleService {
	
	private IRoleDao roleDao;
	SqlSession sqlSession;
	
	public RoleServiceImpl() {
		sqlSession = MyBatisUtil.getSqlSession();
		roleDao = sqlSession.getMapper(IRoleDao.class);
	}

	@Override
	public ServerResponse getRoleList(Integer page,Integer limit) {
		int count = roleDao.findAllRoleCount();
		int offset = (page-1)*limit;
		Map<String, Object> map = new HashMap<>();
		map.put("offset", offset);
		map.put("limit", limit);
		List<Role> data = roleDao.getRoleList(map);
		if (null == data) {
			return ServerResponse.createError("获取失败");
		}
		return ServerResponse.createSuccess("获取成功", count, data);
	}

	@Override
	public ServerResponse deleteById(Integer id) {
		int count = roleDao.deleteById(id);
		if (count <= 0) {
			return ServerResponse.createError("删除失败");
		}
		return ServerResponse.createSuccess("删除成功");
	}

	@Override
	public Role toUpdate(Integer id) {
		return roleDao.toUpdate(id);
	}

	@Override
	public ServerResponse roleUpdate(Role role) {
		int count = roleDao.roleUpdate(role);
		if (count <= 0) {
			return ServerResponse.createError("修改失败");
		}
		return ServerResponse.createSuccess("修改成功");
	}

	@Override
	public ServerResponse roleAdd(Role role) {
		int count = roleDao.roleAdd(role);
		if (count <= 0) {
			return ServerResponse.createError("添加失败");
		}
		return ServerResponse.createSuccess("添加成功");
	}

	@Override
	public ServerResponse deleteAll(String ids) {
		String[] array = ids.split(",");
		for (String id : array) {
			roleDao.deleteById(Integer.parseInt(id));
		}
		return ServerResponse.createSuccess("删除成功");
	}

}
